﻿using System;
using Microsoft.Devices.Sensors;
using System.Windows.Media;
using System.Windows;

namespace Experiments.MichaelKappel.Net.Tilt.Axis
{
    public class AxisGraphInfo : AxisGraphBasicInfo, IDisposable
    {
        private PlaneProjection UIPlane;
        private Accelerometer Accelerometer;
        public event EventHandler<ReadingChangedEventArgs> ReadingChanged;

        public Boolean ShowOffsetOnlyX
        {
            get;
            set;
        }
        public Boolean ShowOffsetOnlyY
        {
            get;
            set;
        }
        public Boolean ShowOffsetOnlyZ
        {
            get;
            set;
        }

        public AxisGraphInfo(Accelerometer accelerometer, PlaneProjection plane)
            : base()
        {
            accelerometer.ReadingChanged += new EventHandler<AccelerometerReadingEventArgs>(accelerometer_ReadingChanged);
            AxisRaw = new AxisInfo();
            AxisOffset = new AxisDegreeInfo();
            UIPlane = plane;
        }
        private void accelerometer_ReadingChanged(object sender, AccelerometerReadingEventArgs e)
        {
            Deployment.Current.Dispatcher.BeginInvoke(() => updateScreen(sender, e));
        }
        private void updateScreen(object sender, AccelerometerReadingEventArgs e)
        {
            AxisRaw = new AxisInfo(e.X,e.Y,e.Z);

            Double x = (ShowOffsetOnlyX) ? AxisOffset.X : GetMappedAxis(MappingX) * ((InverseX) ? -1 : 1);
            Double y = (ShowOffsetOnlyY) ? AxisOffset.Y : GetMappedAxis(MappingY) * ((InverseY) ? -1 : 1);
            Double z = (ShowOffsetOnlyZ) ? AxisOffset.Z : GetMappedAxis(MappingZ) * ((InverseZ) ? -1 : 1);

            Axis = AxisDegreeInfo.ConvertToDegreeInfo(new AxisInfo(x, y, z));

            UIPlane.RotationX = Axis.X + AxisOffset.X;
            UIPlane.RotationY = Axis.Y + AxisOffset.Y;
            UIPlane.RotationZ = Axis.Z + AxisOffset.Z;

            ReadingChanged.Invoke(sender, new ReadingChangedEventArgs(this));
        }
        public void Dispose()
        {
            Accelerometer.ReadingChanged -= new EventHandler<AccelerometerReadingEventArgs>(accelerometer_ReadingChanged);
        }
    }
}